import {valueEquals} from '/src/utils/elementui.js'
import {objDeepCopy} from '/src/utils/index.js'
import merge from '/src/utils/merge.js'
import {reactive} from "vue"

const DefaultProps = {
  value: '',
  label: '',
}

export function useUserDepHook(properties, emits) {
  const userDeptOptionData = reactive({
    selectedList: [],
    // 意思可能是未选中的部门数据，原来是otherValue，改成unselectedList
    unselectedList: [],
    checkedDeptList: [],

    // 点击下一页时，忽略change
    ignoreChangeEvent: false
  })

  const config = computed(() => {
    return merge({...DefaultProps}, properties.props || {})
  })

  // 监听默认选中的数据
  // 如果传入的已选中数据和本地的已选中数据不同，那么设置本地已选中数据
  watch(() => properties.selectedDataList, (val) => {
    if (!valueEquals(properties.selectedDataList, userDeptOptionData.selectedList)) {
      userDeptOptionData.selectedList = objDeepCopy(properties.selectedDataList)
      getCurrentAndOtherValue(false)
    } else {
    }
  }, {
    immediate: true
  })

  watch(() => userDeptOptionData.selectedList, (val) => {
    getCurrentAndOtherValue(false)
  })

  // 如果传入的dataList改变了，表示可能环了部门，导致可选择的部门和人员不同了
  watch(() => properties.dataList, () => {
    if (!properties.dataList) {
      // 没有数据初始化当前值
      console.log("userDeptOptionData", userDeptOptionData)
      userDeptOptionData.checkedDeptList = []
      return
    }
    nextTick(() => {
      getCurrentAndOtherValue()
    }).then(r => {
    })
  })

  // 监听checkedDeptList
  watch(() => userDeptOptionData.checkedDeptList, (newVal, oldVal) => {
    // 如果传入的所有数据dataList没有，返回
    if (!properties.dataList) {
      return
    }
    if (properties.radio) {
      if (userDeptOptionData.unselectedList.length > 0) {
        // 阻挡触发change事件
        userDeptOptionData.ignoreChangeEvent = true
        userDeptOptionData.unselectedList = []
        nextTick(() => {
          userDeptOptionData.ignoreChangeEvent = false
        }).then(r => {
        })
      }
      // change
      if (userDeptOptionData.checkedDeptList.length > 1) {
        userDeptOptionData.checkedDeptList =
            userDeptOptionData.checkedDeptList.length ?
                [userDeptOptionData.checkedDeptList[userDeptOptionData.checkedDeptList.length - 1]] :
                []
        return
      }
    }

    // 触发change  和 input 事件
    // 如果选择的数量和所有的数据相同，那么就发送全部选中的消息
    emitAllSelectFlagChange(properties.dataList.length > 0 && properties.dataList.length === userDeptOptionData.checkedDeptList.length)

    if (!userDeptOptionData.ignoreChangeEvent) {
      // 如果新旧值相同
      if (!valueEquals(newVal, oldVal)) {
        // change
        console.log("userDeptOptionData.checkedDeptList", userDeptOptionData.checkedDeptList)
        console.log("userDeptOptionData.checkedDeptList", userDeptOptionData.unselectedList)
        emitCheckboxSelectChange([...userDeptOptionData.checkedDeptList, ...userDeptOptionData.unselectedList])
      }
    }
  }, {deep: true})

  // 监听unselectedList
  watch(() => userDeptOptionData.unselectedList, (newVal, oldVal) => {
    // 如果传入的所有数据dataList没有，返回
    if (!properties.dataList) {
      return
    }
    if (properties.radio) {
      const needChange = (userDeptOptionData.checkedDeptList.length + userDeptOptionData.unselectedList.length) > 1
      if (needChange) {
        if (userDeptOptionData.checkedDeptList.length > 0) {
          // 阻挡触发change事件
          userDeptOptionData.ignoreChangeEvent = true
          userDeptOptionData.checkedDeptList = []
          nextTick(() => {
            userDeptOptionData.ignoreChangeEvent = false
          }).then(r => {
          })
        }

        if (userDeptOptionData.unselectedList.length > 1) {
          userDeptOptionData.unselectedList =
              userDeptOptionData.unselectedList.length ?
                  [userDeptOptionData.unselectedList[userDeptOptionData.unselectedList.length - 1]] :
                  []
        }
        return
      }
    }

    // 触发change  和 input 事件
    if (!valueEquals(newVal, oldVal) && !userDeptOptionData.ignoreChangeEvent) {
      emitCheckboxSelectChange([...userDeptOptionData.checkedDeptList, ...userDeptOptionData.unselectedList])
    }
  }, {deep: true})


  onMounted(() => {
    userDeptOptionData.selectedList = objDeepCopy(properties.selectedDataList || [])
    getCurrentAndOtherValue(true)
  })


  function emitAllSelectFlagChange(flag) {
    emits('allSelectFlagChange', flag)
  }

  /**
   * 勾选
   */
  function emitCheckboxSelectChange(val) {
    userDeptOptionData.selectedList = val
    nextTick(() => {
      emits('selectedChange', objDeepCopy(userDeptOptionData.selectedList))
    }).then(r => {
    })
  }

  /**
   * 搜索选择
   */
  function searchSelect(item) {
    const id = item[config.value.value]
    const listIds = properties.dataList.map(item => item[config.value.value])
    if (listIds.includes(id)) {
      if (!userDeptOptionData.checkedDeptList.includes(id)) {
        userDeptOptionData.checkedDeptList = [...userDeptOptionData.checkedDeptList, id]
      }
    } else {
      if (!userDeptOptionData.unselectedList.includes(id)) {
        userDeptOptionData.unselectedList = [...userDeptOptionData.unselectedList, id]
      }
    }
  }


  /**
   * 全部勾选
   */
  function handleCheckAllChange(val) {
    if (properties.dataList && properties.dataList.length > 0) {
      if (val) {
        const checkList = properties.dataList.map(item => item[config.value.value])
        if (!valueEquals(userDeptOptionData.checkedDeptList, checkList)) {
          userDeptOptionData.checkedDeptList = checkList
        }
      } else {
        userDeptOptionData.checkedDeptList = []
      }
    }
  }

  /**
   * 获取当前值和其他值
   * 因为存在传入的部门或者人员不只在当前选择的部门下，所以在发消息的时候，要带上别的部门下的选择的人员。
   * 这个情况在单选下不会发生，只会发生在多选的场景下。
   * 比如已经选择了部门1下的张三，现在到部门2下选择李四，在选择李四后，发送消息的时候，要记得把部门1下的张三带过去。
   *
   */
  function getCurrentAndOtherValue(ignoreChangeEvent = true) {
    if (!properties.dataList) {
      return
    }
    userDeptOptionData.ignoreChangeEvent = ignoreChangeEvent
    // 解析当前列的值
    const checkedList = [] //本部门下选择的部门或人员
    const otherValue = []  //不在本部门下选择的部门或人员
    // listIds表示传入的所有可选择部门或人员的id
    const listIds = properties.dataList.map(item => item[config.value.value])
    if (userDeptOptionData.selectedList && userDeptOptionData.selectedList.length > 0) {
      userDeptOptionData.selectedList.forEach(id => {
        if (listIds.includes(id)) {
          checkedList.push(id)
        } else {
          otherValue.push(id)
        }
      })
    }
    if (!valueEquals(userDeptOptionData.unselectedList, otherValue)) {
      userDeptOptionData.unselectedList = otherValue
    }
    if (!valueEquals(userDeptOptionData.checkedDeptList, checkedList)) {
      userDeptOptionData.checkedDeptList = checkedList
    }

    nextTick(() => {
      userDeptOptionData.ignoreChangeEvent = false
    }).then(r => {
    })
  }

  return {
    userDeptOptionData, config, searchSelect, handleCheckAllChange, getCurrentAndOtherValue

  }
}
